package com.sunday.common.mq.kafka.study.spring.e17_Default_Error_Handler;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.kafka.core.KafkaTemplate;
import org.springframework.kafka.support.SendResult;
import org.springframework.retry.support.RetryTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Random;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

/**
 * {@link org.springframework.boot.autoconfigure.kafka.KafkaAutoConfiguration}
 */
@Slf4j
@RestController
@RequestMapping("/test")
public class MQApi {

    private final Random rand = new Random();

    @Autowired
    private KafkaTemplate<Object, Object> kafkaTemplate;

    @Autowired
    private RetryTemplate retryTemplate;

    @GetMapping("/send/{topic}/{key}")
    public void send(@PathVariable String topic, @PathVariable String key) throws InterruptedException, ExecutionException {
        retryTemplate.execute(context -> {

            log.info("============结束访问================");
            throw new RuntimeException("error");

//            try {
//                CompletableFuture<SendResult<Object, Object>> future;
//                ValidatedClass validatedClass = new ValidatedClass(rand.nextInt(2));
//                log.info("send : {}", validatedClass);
//                future = kafkaTemplate.send(topic, key, validatedClass.toString());
//                log.info("{}", future.get());
//                log.info("============结束访问================");
//                return null;
////                future.whenComplete((result, throwable) -> log.info("[whenComplete] result : {}, throwable : {}", result, throwable, throwable));
//            } catch (Exception e) {
//                throw new RuntimeException(e);
//            }
        });
    }

    @KafkaListener(
            id = "myId_11",
            topics = "topic11",
            clientIdPrefix = "TEST11"
    )
//    public void listen11(@Payload ValidatedClass validatedClass) {
    public void listen11(String validatedClass) {
        log.info("[validatedClass] : {}", validatedClass);
    }

}
